import {
  _decorator,
  instantiate,
} from "cc";
import DataManager from "../../Global/DataManager";
import { EntityTypeEnum, IActor, InputTypeEnum } from "../../Common";
import { EntityManager } from "../../Base/EntityManager";
import { ActorStateMachine } from "./ActorStateMachine";
import { EntityStateEnum } from "../../Enum";
import { WeaponManager } from "../Weapon/WeaponManager";
import { rad2Angle } from "../../Utils";
const { ccclass, property } = _decorator;

@ccclass("ActorManager")
export class ActorManager extends EntityManager {
  bulletType: EntityTypeEnum
  private wm: WeaponManager
  init(data: IActor) {
    this.bulletType = data.bulletType
    this.fsm = this.addComponent(ActorStateMachine);
    this.fsm.init(data.type);
    this.state = EntityStateEnum.Idle;
    const prefab = DataManager.Instance.prefabMap.get(EntityTypeEnum.Weapon1)
    const weapon = instantiate(prefab)
    weapon.setParent(this.node)
    this.wm = weapon.addComponent(WeaponManager)
    this.wm.init(data)
  }
  tick(dt) {
    // 玩家操作摇杆，这里的值才不是0，不是0就是true
    if (DataManager.Instance.jm.input.length()) {
      const { x, y } = DataManager.Instance.jm.input;
      DataManager.Instance.applyInput({
        id: 1,
        type: InputTypeEnum.ActorMover,
        direction: { x, y },
        dt,
      });
      this.state = EntityStateEnum.Run;
    } else {
      this.state = EntityStateEnum.Idle;
    }
  }
  render(data: IActor) {
    const { direction, position } = data;
    this.node.setPosition(position.x, position.y);
    // 如果玩家有操作摇杆，根据摇杆渲染玩家的方向
    if (direction.x !== 0) this.node.setScale(direction.x > 0 ? 1 : -1, 1);
    // 斜面 = 开方(方向的x的平方加上方向的y的平方)
    const side = Math.sqrt(direction.x ** 2 + direction.y ** 2)
    // 弧度 = 反三角函数(斜面分之对边)
    const rad = Math.asin(direction.y / side)
    const angle = rad2Angle(rad)
    this.wm.node.setRotationFromEuler(0, 0, angle)
  }
}
